﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace Alerts_Administration_2010.classes.views.Controls
{
    public class AlertFrequencyField : DataControlField
    {
        private RadioButtonList rblFrequency;
        private Panel panel;
        private DropDownList ddlDays;
        private DropDownList ddlHours;

        protected override DataControlField CreateField()
        {
            return new AlertFrequencyField();
        }

        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {
            base.InitializeCell(cell, cellType, rowState, rowIndex);

            if (cellType == DataControlCellType.DataCell)
            {
                if ((rowState & DataControlRowState.Edit) == DataControlRowState.Edit)
                {
                    
                    this.ddlDays = new DropDownList() 
                    {
                     //   ID = "ddlDays" 
                    };
                    
                    this.ddlHours = new DropDownList() 
                    {
                      //  ID = "ddlHours"
                    };

                    this.rblFrequency = new RadioButtonList()
                    {
                        AutoPostBack = true,
                       // ID = "rblFrequency"
                    };

                    this.rblFrequency.PreRender += new EventHandler(_rbl_PreRender);
                    this.rblFrequency.DataBinding += new EventHandler(_rbl_DataBinding);
                    
                    this.panel = new Panel();
                    this.panel.Controls.Add(rblFrequency);
                    this.panel.Controls.Add(ddlHours);
                    this.panel.Controls.Add(ddlDays);

                    cell.Controls.Add(this.panel);
                }
            }
        }

        private void _rbl_PreRender(object sender, EventArgs e)
        {
            this.ddlDays.Enabled = this.rblFrequency.SelectedValue == SPAlertFrequency.Weekly.ToString();
            this.ddlHours.Enabled = this.rblFrequency.SelectedValue!= SPAlertFrequency.Immediate.ToString(); 
        }

        private void _rbl_DataBinding(object sender, EventArgs e)
        {
            Control container = ((Control)sender).NamingContainer;
            object dataItem = DataBinder.GetDataItem(container);
            Dictionary<string, string> values = DataBinder.GetPropertyValue(dataItem, "AlertFrequencies") as Dictionary<string, string>;
            string alertFrequency = DataBinder.GetPropertyValue(dataItem, "AlertFrequency") as string;
            DateTime alertTime = (DateTime)DataBinder.GetPropertyValue(dataItem, "AlertTime");

            foreach (KeyValuePair<string, string> pair in values)
            {
                this.rblFrequency.Items.Add(
                    new ListItem(pair.Value, pair.Key)
                    {
                        Selected = alertFrequency.Equals(pair.Key)
                    });
            }

            for (DateTime dt = new DateTime(2010, 9, 19); dt < new DateTime(2010, 9, 26); dt = dt.AddDays(1))
            {
                string dayOfWeek = dt.DayOfWeek.ToString();

                this.ddlDays.Items.Add(new ListItem(dayOfWeek, dayOfWeek)
                {
                    Selected = dayOfWeek.Equals(alertTime.DayOfWeek.ToString())
                });
            }

            for (int i = 0; i < 24; i++)
            {
                this.ddlHours.Items.Add(new ListItem(((i + 11) % 12 + 1).ToString("00") + ":00 " + ((i / 12) == 0 ? "AM" : "PM"), i.ToString())
                {
                    Selected = alertTime.Hour.Equals(i)
                });
            }
        }

        public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
        {
            base.ExtractValuesFromCell(dictionary, cell, rowState, includeReadOnly);

            dictionary.Add("AlertFrequency", this.rblFrequency.SelectedItem.Value);

            switch (rblFrequency.SelectedValue)
            {
                case "Daily":
                    {
                        int hour = int.Parse(this.ddlHours.SelectedValue);
                        DateTime potentialAlertTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, 0, 0);
                        if (DateTime.Now >= potentialAlertTime)
                        {
                            potentialAlertTime = potentialAlertTime.AddDays(1);
                        }

                        dictionary.Add("AlertTime", potentialAlertTime);
                        break;
                    }
                case "Immediate":
                    break;
                case "Weekly":
                    {
                        int hour = int.Parse(ddlHours.SelectedValue);
                        DateTime potentialAlertTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, 0, 0);
                        while ((DateTime.Now > potentialAlertTime) || (potentialAlertTime.DayOfWeek.ToString() != ddlDays.SelectedValue))
                        {
                            potentialAlertTime = potentialAlertTime.AddDays(1);
                        }
                        dictionary.Add("AlertTime", potentialAlertTime);
                        break;
                    }
                default:
                    throw new ArgumentOutOfRangeException();
            }

        }
    }
}
